﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using Technewlogic.FileXChange.Common;

namespace Technewlogic.FileXChange.HttpClient
{
	class Program
	{
		static void Main(string[] args)
		{
			if (args.Count() < 3)
				Console.WriteLine("Usage: HttpClient.exe [Method(get, put, delete)] [Url] [Filename] [User(optional)] [PW(optional)]");
			else
			{
				try
				{
					FileMethod method = FileMethod.Parse(args[0]);
					string url = args[1] + "?" + Constants.QueryStringMethod + "=" + method.Name;
					string file = args[2];
					string userName = null;
					string password = null;
					if (args.Length > 3)
					{
						userName = args[3];
						if (args.Length > 4)
							password = args[4];

						DoRequest(url, file, method, userName, password);
					}
					else
						DoRequest(url, file, method);
				}
				catch (Exception ex)
				{
					Console.WriteLine("Fehler: " + ex.Message);
				}
			}
		}

		private static void DoRequest(string url, string file, FileMethod method)
		{
			DoRequest(url, file, method, null, null);
		}

		private static void DoRequest(string url, string file, FileMethod method, string userName, string password)
		{
			FileService fileService = new FileService(url);

			if (string.IsNullOrEmpty(userName))
				fileService.Credentials = System.Net.CredentialCache.DefaultCredentials;
			else
				fileService.Credentials = new NetworkCredential(userName, password);

			if (method == FileMethod.Put)
			{
				using (FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read))
				{
					byte[] buffer = new byte[fs.Length];
					fs.Read(buffer, 0, (int)fs.Length);

					fileService.Post(Path.GetFileName(file), buffer);
				}
			}
			else if (method == FileMethod.Delete)
			{
				fileService.Delete(Path.GetFileName(file));
			}
			else if (method == FileMethod.Get)
			{
				throw new NotImplementedException("Get is not implemented.");
			}
		}
	}
}